package com.chendx.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.client.utils.StringUtils;
import com.chendx.model.behavior.dtos.BehaviorEntryDto;
import com.chendx.model.behavior.pojos.ApBehaviorEntry;
import com.chendx.model.common.dtos.ResponseResult;
import com.chendx.model.common.enums.AppHttpCodeEnum;
import com.chendx.model.search.dtos.UserSearchDto;
import com.chendx.model.user.pojos.ApUser;
import com.chendx.search.feign.BehaviorFeign;
import com.chendx.search.service.ApUserSearchService;
import com.chendx.search.service.ArticleSearchService;
import com.chendx.utils.AppThreadLocalUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by chendx on 2022/3/15.
 */
@Service
public class ApArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ApUserSearchService apUserSearchService;
    @Autowired
    private BehaviorFeign behaviorFeign;
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        if (dto == null || StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //只有在首页查询的时候才会保存
        if (dto.getFromIndex() == 0){
            ApBehaviorEntry apBehaviorEntry = getEntry(dto);
            if(apBehaviorEntry == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            apUserSearchService.insert(apBehaviorEntry.getEntryId(),dto.getSearchWords());
        }
        //2.从es索引库中检索数据
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //布尔查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //根据关键字分词查询--》title  content
        QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery(dto.getSearchWords()).field("title").field("content").defaultOperator(Operator.OR);
        boolQueryBuilder.must(queryStringQueryBuilder);
        //查询小于minBehotTime的数据
      //  RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime());
      //  boolQueryBuilder.filter(rangeQueryBuilder);
        searchSourceBuilder.query(boolQueryBuilder);
        //排序
        searchSourceBuilder.sort("publishTime", SortOrder.DESC);
        //分页
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(dto.getPageSize());
        searchRequest.source(searchSourceBuilder);

        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //3.封装返回

        List<Map> articleList = new ArrayList<>();
        SearchHits hits = searchResponse.getHits();
        System.out.println("HIT " + JSON.toJSONString(hits));
        for (SearchHit searchHit : hits){
            String sourceAsString = searchHit.getSourceAsString();
            System.out.println("sourceAsString "+ sourceAsString);
            Map map = JSON.parseObject(sourceAsString, Map.class);
            articleList.add(map);
        }

        return ResponseResult.okResult(articleList);
    }

    private ApBehaviorEntry getEntry(UserSearchDto userSearchDto) {
        BehaviorEntryDto dto = new BehaviorEntryDto();
        ApUser apUser = AppThreadLocalUtils.get();
        if (apUser != null && apUser.getId() != null) {
            dto.setUserId(apUser.getId());
        }
        dto.setEquipmentId(userSearchDto.getEquipmentId());
        ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(dto);
        return apBehaviorEntry;
    }

}
